package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.query.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired@SuppressWarnings("all")
    private PermissionMapper permissionMapper;

    @Autowired
    private ApplicationContext ctx;
    @Override
	public void reload() {
		//1先查询当前数据库中所有的权限表达式
		List<String> allExpersion = permissionMapper.selectExpressions();
		//2 从Spring容器中取出所有的控制器对象
		Collection<Object> ctrls = ctx.getBeansWithAnnotation(Controller.class).values();
		//3 遍历控制器里的每个方法
		for (Object ctrl : ctrls) {
			//拿到当前类声明的每一个方法
			//ctrl是代理对象,需要通过getSuperclass()拿到父类对象(真实对象)
			Method[] ms = ctrl.getClass().getSuperclass().getDeclaredMethods();
			for (Method m : ms) {
				//4 尝试从该方法中获取权限注解
				RequiresPermissions anno = m.getAnnotation(RequiresPermissions.class);
				//5 如果该方法贴有权限注解并且数据库中不存在,则生产权限对象
				if (anno != null) {
					String expression = anno.value()[0]; //从shiro注解中获取第0个元素
					if (!allExpersion.contains(expression)) {
						Permission p = new Permission();
						p.setName(anno.value()[1]);//权限名称 从shiro的注解中获取第一个元素
						p.setExpression(expression);
						//6 把该对象保存到数据库
						permissionMapper.insert(p);
					}
				}
			}
		}
	}

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }



    @Override
    public PageInfo queryForList(QueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> permissions = permissionMapper.queryForList(qo);
        return new PageInfo(permissions);
    }
}
